import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Video, VideoComment } from '@/services/video/video.types'
import services from '@/services'

export const useVideoStore = defineStore('video', () => {
  // 状态
  const videoList = ref<Video[]>([])
  const currentVideo = ref<Video | null>(null)
  const currentComments = ref<VideoComment[]>([])
  const loading = ref(false)
  const commentsLoading = ref(false)
  const currentPage = ref(1)
  const pageSize = ref(10)
  const hasMore = ref(true)

  // 计算属性
  const totalVideos = computed(() => videoList.value.length)

  // 加载视频列表
  async function loadVideos(page: number = 1, size: number = 10) {
    if (loading.value) return

    try {
      loading.value = true
      const response = await services.video.getVideoList({
        page,
        pageSize: size,
      })

      if (page === 1) {
        videoList.value = response.data
      } else {
        videoList.value.push(...response.data)
      }

      hasMore.value = response.data.length === size
      currentPage.value = page
      pageSize.value = size
    } catch (error) {
      console.error('Failed to load videos:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 加载更多视频
  async function loadMoreVideos() {
    if (hasMore.value && !loading.value) {
      await loadVideos(currentPage.value + 1, pageSize.value)
    }
  }

  // 加载视频详情
  async function loadVideoById(id: number) {
    try {
      loading.value = true
      const video = await services.video.getVideoById(id.toString())
      currentVideo.value = video
      return video
    } catch (error) {
      console.error('Failed to load video:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 加载评论列表
  async function loadComments(videoId: number, page: number = 1, size: number = 20) {
    try {
      commentsLoading.value = true
      const response = await services.video.getComments(videoId, page, size)
      if (page === 1) {
        currentComments.value = response.list
      } else {
        currentComments.value.push(...response.list)
      }
      return response
    } catch (error) {
      console.error('Failed to load comments:', error)
      throw error
    } finally {
      commentsLoading.value = false
    }
  }

  // 发布评论
  async function addComment(videoId: number, content: string, parentId: number = 0) {
    try {
      const response = await services.video.addComment(videoId, parentId, content)
      if (response.code === 0) {
        // 重新加载评论列表
        await loadComments(videoId)
      }
      return response
    } catch (error) {
      console.error('Failed to add comment:', error)
      throw error
    }
  }

  // 删除评论
  async function deleteComment(videoId: number, commentId: string) {
    try {
      const response = await services.video.deleteComment(commentId)
      if (response.code === 0) {
        // 从列表中移除评论
        currentComments.value = currentComments.value.filter(
          (comment) => comment.id.toString() !== commentId,
        )
      }
      return response
    } catch (error) {
      console.error('Failed to delete comment:', error)
      throw error
    }
  }

  // 更新视频状态（点赞、收藏等）
  function updateVideoState(videoId: number, updates: Partial<Video>) {
    // 更新视频列表中的视频
    const index = videoList.value.findIndex((v) => v.id === videoId)
    if (index !== -1) {
      videoList.value[index] = { ...videoList.value[index], ...updates }
    }

    // 更新当前视频
    if (currentVideo.value?.id === videoId) {
      currentVideo.value = { ...currentVideo.value, ...updates }
    }
  }

  // 重置状态
  function reset() {
    videoList.value = []
    currentVideo.value = null
    currentComments.value = []
    loading.value = false
    commentsLoading.value = false
    currentPage.value = 1
    hasMore.value = true
  }

  return {
    // 状态
    videoList,
    currentVideo,
    currentComments,
    loading,
    commentsLoading,
    currentPage,
    pageSize,
    hasMore,

    // 计算属性
    totalVideos,

    // 方法
    loadVideos,
    loadMoreVideos,
    loadVideoById,
    loadComments,
    addComment,
    deleteComment,
    updateVideoState,
    reset,
  }
})
